package hust.rpc.client.pull;


import hust.rpc.client.ClientBootStrap;
import hust.rpc.client.loadbalance.LoadBalance;
import hust.rpc.client.loadbalance.PollingLoadBalance;
import hust.rpc.client.loadbalance.RandomLoadBalance;
import hust.rpc.common.Address;
import hust.rpc.common.HelloService;
import hust.rpc.common.RegistryCenter;
import hust.rpc.procotol.JsonRpcRequest;
import hust.rpc.procotol.JsonRpcResponse;
import hust.rpc.util.JsonUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class PullServiceHandle extends ChannelInboundHandlerAdapter {

    /**
     * 用来存储服务提供方的地址
     */
    private static HashMap<String, Set<Address>> serviceMap = new HashMap<>();

    /**
     * 用来存储服务提供方的地址
     */
    private static HashMap<String , List<Address>> map = new HashMap<>();

//    private static LoadBalance loadBalance = new PollingLoadBalance();
    private static LoadBalance loadBalance = new RandomLoadBalance();

    /**
     * 进行拉取服务
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("开始拉取服务...");

        JsonRpcRequest request = new JsonRpcRequest.Builder()
                .withId("123456")
                .withMethod(RegistryCenter.class.getName() + ".searchService")
                .withParams(HelloService.class.getName())
                .build();
        ctx.writeAndFlush(JsonUtil.writeRequestAsString(request));
    }

    /**
     * 尚未写解析 Response 的方法，先进行直接打印
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        JsonRpcResponse response = JsonUtil.readResponseFromString((String) msg);
        if (response != null){
            String result = response.getResult();

            List<Address> list = JsonUtil.readListFromString(result, Address.class);
            map.put(HelloService.class.getName(),list);
            System.out.println(map);
            loadBalance.setMap(map);

//            HashSet<Address> set = JsonUtil.readSetFromAddress(result, Address.class);
//            serviceMap.put(HelloService.class.getName(),set);
//            System.out.println(serviceMap);
            System.out.println("拉取服务成功");
            ClientBootStrap.c.countDown();


//            loadBalance.setServiceMap(serviceMap);
        }
    }



    /**
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
